package com.mycompany.myapp.web.rest.controller;

import com.alibaba.fastjson.JSONObject;
import com.mycompany.myapp.config.ApplicationProperties;
import com.mycompany.myapp.service.UserService;
import com.mycompany.myapp.web.rest.utils.ResultObj;
import com.mycompany.myapp.web.rest.utils.TypeUtils;
import com.mycompany.myapp.web.rest.utils.UploadUtils;
import io.micrometer.core.annotation.Timed;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URISyntaxException;

/**
 * 上传文件控制类
 */

@Api(tags = "上传文件")
@RestController
@RequestMapping("/api")
public class UploadController {
    private final ApplicationProperties applicationProperties;
    private final UserService userService;
    private static Logger logger = LoggerFactory.getLogger(UploadUtils.class);
    private static String fileName;

    public UploadController(ApplicationProperties applicationProperties, UserService userService) {
        this.applicationProperties = applicationProperties;
        this.userService = userService;
        fileName = applicationProperties.getAdvertise();     //ad文件名
    }

    /**
     * 上传图片
     *
     * @param myfile
     * @return
     * @throws URISyntaxException
     */
    @ApiOperation("上传图片 RequestParam")
    @PostMapping("/permit/upload/avatar")
    @Timed
    public ResultObj uploadPic(@ApiParam(name = "file", value = "上传文件", required = true) HttpServletRequest request, @RequestParam MultipartFile myfile) throws URISyntaxException {
        new File(UploadUtils.getFullPath(applicationProperties.getFilepath(), applicationProperties.getAdvertise())).mkdirs();                               //创建文件夹
        logger.debug("Filepath: " + applicationProperties.getFilepath());
        logger.debug("Avatorpath: " + applicationProperties.getAdvertise());
//        logger.debug("email: " + email);
        if (!TypeUtils.isEmpty(myfile)) {
            String folder = fileName;
            String url = UploadUtils.uploadDoc(myfile, folder);
            String fullUrl = applicationProperties.getFileprefix() + url;
//            userService.updateAvator(email, fullUrl);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url", fullUrl);
            return ResultObj.back(200, jsonObject);
        }

        return ResultObj.back(200, null);
    }

}
